<?php
namespace app\admin\controller;
use app\common\model\UserRole;
use think\Db;
use think\Request;
class Notice extends Common
{

    public function index(){
        $role = UserRole::getRoleSelect();
        if(Request::instance()->isAjax()){
            $data = array_filter(input('','','trim'));
            $data['role_id'] = session('user.role_id');
            $data= \app\common\model\Notice::getList($data);
            return arrayNumericFormat($data);
        }
        return view('',['role'=>$role]);
    }



    public function create(){
        $this->view->engine->layout('common/iframe');
        $role = UserRole::getRoleSelect();
        return view('',['role'=>$role]);
    }



    public function detail(){
        try{
            $this->view->engine->layout('common/iframe');
            $id = input('id');
            if(empty($id)){
                exception('错误请求');
            }
            $notice = \app\common\model\Notice::get($id);
            if(empty($notice)){
                exception('信息不存在');
            }
            $role = UserRole::getRoleSelect();
            return view('',['data'=>$notice,'role'=>$role]);
        }catch (\Exception $e) {
            return view('common/error',['msg' => $e->getMessage()]);
        }

    }




    public function save(){
        try{
            $data = input('post.','','trim');
            Db::startTrans();
            $data['user_id'] = $this->userId;
            $data['is_sms'] = isset($data['is_sms'])?$data['is_sms']:2;
            $notice = new \app\common\model\Notice();
            if($notice->allowField(true)->force()->save($data) ===false){
                throw new \think\Exception('保存失败');
            }
            $user_ids =\app\common\model\User::where(['role_id'=>$data['role_id'],'status'=>1])->column('id');
            $notice_log = [];
            foreach ($user_ids as $k => $v){
                $notice_log[$k] = [
                    'notice_id'=>$notice['id'],
                    'user_id'=>$v,
                    'create_time'=>date('Y-m-d H:i:s'),
                ];
            }
            Db::name('notice_log')->insertAll($notice_log);

            //如果开启短信通知
//            if($data['is_sms'] == 1){
//                $tplId =  Config::get('sms_tpl_id.notice');
//                $mobile_array =\app\common\model\User::where(['role_id'=>$data['role_id'],'status'=>1])->column('mobile');
//                $smsRes = alsms($tplId, $mobile_array, ['title'=>$data['title'],'content'=>$data['content']]);
//
//            }

            $result['msg'] = '操作成功';
            $result['code'] = 0;
            Db::commit();
            return  json($result);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'msg' => $e->getMessage(), 'data' => []]);
        }

    }

}
